package ua.kharkov.knure.pereverziev.diploma.web.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.i18n.RManager;

/**
 * I18n support.
 * 
 * @author A.Pereverziev
 * 
 */
public class I18nTag extends TagSupport {

	private static final long serialVersionUID = -2433202077324542435L;

	private static final Logger log = Logger.getLogger(I18nTag.class);

	private String key;

	private String locale;

	public void setKey(final String key) {
		this.key = key;
	}

	public void setLocale(final String locale) {
		this.locale = locale;
	}

	@Override
	public int doStartTag() throws JspException {
		log.trace("Tag attribute value: key --> " + key);
		log.trace("Tag attribute value: locale --> " + locale);

		final JspWriter writer = pageContext.getOut();
		try {

			if (locale == null) {
				final String currentLocale = (String) pageContext.getSession()
						.getAttribute("currentLocale");
				log.trace("Session attribute: currentLocale --> "
						+ currentLocale);

				// if there is no currentLocale
				if (currentLocale == null) {
					final String defaultLocaleName = RManager
							.getDefaultLocaleName();
					pageContext.getSession().setAttribute("currentLocale",
							defaultLocaleName);
					log.debug("Session attribute set: currentLocale --> "
							+ defaultLocaleName);
				}
				locale = currentLocale;
			}

			String propertyValue = null;
			try {
				propertyValue = RManager.getProperty(key, locale);
				log.trace("Obtain property value --> " + propertyValue);
				writer.print(propertyValue);
			} catch (final Exception ex) {
				writer.print(key);
				log.warn("Cannot find property value for key --> " + key);
			}
		} catch (final IOException ex) {
			ex.printStackTrace();
		} finally {
			locale = null;
		}
		return SKIP_BODY;
	}
}